//
// Created by lau on 2019-10-18.
//

#include "grayfilter.h"
#include "glutils/render.h"
#include "utils/logutils.h"

namespace VideoEffect {

    void GrayFilter::setContext(Context *context) {
        mContext = context;
    }

    void GrayFilter::initFilter() {
        mProgram = new Program();
        mProgram->init(VERTEXT_SHADER, FRAGMENT_SHADER);
    }

    void GrayFilter::rendFrame(_VE_TEXTURE *textureIn, _VE_TEXTURE *textureOut) {

        GLuint fboId = mContext->getFrameBuffer()->mFboId;

        glBindFramebuffer(GL_FRAMEBUFFER, fboId);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureOut->textureID, 0);
        GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
        if (status != GL_FRAMEBUFFER_COMPLETE) {
            VE_LOGE("Framebuffer not complete");
        }

        VEUInt32 width = textureOut->width;
        VEUInt32 height = textureOut->height;
        VEUInt32 target = textureOut->target;

        glViewport(0, 0, width, height);
        glClearColor(0.3f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        glBindBuffer(textureOut->target, textureOut->textureID);

        mProgram->use();
        mProgram->setUniformTexture("uTexture0", 0, textureIn->textureID, target);
        Render *render = mContext->getRender();
        render->draw(mProgram);

    }

}
